﻿using Nancy.Json;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;

namespace CloudSharingStation_UWP_.Model
{
    class ResourceList
    {
        public List<StudyResource> resources { get; set; }
        public User currentUser;

        /// <summary> 发送Post请求上传文件
        /// </summary>
        /// <param name="localPath"></param>
        /// <param name="studyResource"></param>
        /// <returns></returns>
        public HttpStatusCode UploadFile(string localPath,StudyResource studyResource)
        {
            string url = "https://localhost:" + Config.localNum + "/api/file/upload?localpath="+localPath;
            JavaScriptSerializer json = new JavaScriptSerializer();
            string jsonData = json.Serialize(studyResource); // 将对象转换成json格式
            HttpWebRequest request = null;
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Config.CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.ContentType = "application/json";
            request.UserAgent = Config.DefaultUserAgent;
            // 如果json数据不是null，也非空则写入请求中
            if (!string.IsNullOrEmpty(jsonData))
            {
                using (var postStream = new StreamWriter(request.GetRequestStream()))
                {
                    postStream.Write(jsonData);
                }
            }
            try
            {
                HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
                // Stream resstream = resp.GetResponseStream();
                return resp.StatusCode;
            }
            catch(Exception e1)
            {
                Console.WriteLine(e1);
                return HttpStatusCode.BadRequest;
            }
        }

        /// <summary> 发送Post请求下载文件
        /// </summary>
        /// <param name="remoteFilename"> 需要下载的文件的文件名 如：a.txt </param>
        /// <param name="localPath"> 下载到的本地绝对路径 </param>
        public HttpStatusCode DownloadFile(string remoteFilename, string localPath)
        {
            string url = "https://localhost:" + Config.localNum + "/api/file/download?remoteFilename="+remoteFilename+ "&localPath="+localPath;
            HttpWebRequest request = null;
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Config.CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = Config.DefaultUserAgent;

            try
            {
                HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
                // Stream resstream = resp.GetResponseStream();
                return resp.StatusCode;
            }
            catch(Exception e1)
            {
                Console.WriteLine(e1);
                return HttpStatusCode.BadRequest;
            }
        }
        /// <summary> 按照关键词查询文件
        /// </summary>
        /// <param name="keyWord"></param>
        public void SearchFile(string keyWord)
        {

        }

        /// <summary> 展示服务器上现在有的所有文件
        /// </summary>
        public List<StudyResource> GetAllFilesToShow()
        {
            string url = "https://localhost:" + Config.localNum + "/api/file/list";
            string result = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Config.CheckValidationResult);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ProtocolVersion = HttpVersion.Version10;
            req.Method = "GET";
            req.ContentType = "application/x-www-form-urlencoded";
            req.UserAgent = Config.DefaultUserAgent;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
            List<StudyResource> list = js.Deserialize<List<StudyResource>>(result);
            return list;
        }

        /// <summary>
        /// 发送Get请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="dic">请求参数定义</param>
        /// <returns></returns>
        public  List<StudyResource> SearchFileByConditions(SearchCondition searchCondition)
        {
            string url = "https://localhost:" + Config.localNum + "/api/file/search" ;
            JavaScriptSerializer json = new JavaScriptSerializer();
            string jsonData = json.Serialize(searchCondition); // 将对象转换成json格式
            Dictionary<string, object> parameters = new Dictionary<string, object>();

            parameters.Add("searchCondition", jsonData);
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (parameters.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in parameters)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Config.CheckValidationResult);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
            req.ProtocolVersion = HttpVersion.Version10;
            req.Method = "GET";
            req.ContentType = "application/json";
            req.UserAgent = Config.DefaultUserAgent;
            //添加参数
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                string result;
                Stream stream = resp.GetResponseStream();
                try
                {
                    //获取内容
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                finally
                {
                    stream.Close();
                }
                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                List<StudyResource> list = js.Deserialize<List<StudyResource>>(result);
                return list; // 返回登陆状态码以及token
            }
            catch (System.Net.WebException exception)
            {
                Console.WriteLine(exception.Message);
                return null;
            }
        }
        public void DeleteMyFile()
        {
            // 删除文件的功能本次大作业不做实现
        }

        public void CommentFile()
        {

        }

        public void GetFileIndex()
        {

        }

    }
}
